
package com.zhu.salesmanagement;

import java.util.ArrayList;

import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ObservableScrollView;

import android.app.Activity;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 附件门店
 */

public class NearStoreListActivity extends Activity implements View.OnClickListener {

	private final static String TAG = "VisitTaskListActivity";
	private final static int TASK_LIST_QUERY_TOKEN = 1000;
	private final static int CNAME_LIST_QUERY_TOKEN = 1001;
	private final static int CPOS_LIST_QUERY_TOKEN = 1002;
	private final static int CVISITED_LIST_QUERY_TOKEN = 1003;
	private final static int CREMIND_LIST_QUERY_TOKEN = 1004;
	private final static int TASK_LIST_DELETE_TOKEN = 2000;

	private static final int UPDATE_DB = 1000;

	private boolean isChange = false;
    private ObservableScrollView mScrollView;
    private LinearLayout mBodyLinearLayout = null;
    private ArrayList<VisitTaskInfo> mVisitTaskList = null;
    private View mCheckView = null;
    private Spinner mSpinner = null; 
    private FrameLayout mFrameLayout = null;
    private MyLocation mMyLocation = null;
    private Location mCurLocation = null;
    private VisitTaskInfo mCheckingVisitTaskInfo = null;
    private ImageView mCheckingButtom = null;
    private int mCurCheckType = -1;
    private boolean isChecking = false;
    private AnimationDrawable mAnimation = null;
    private TextView mNoneText = null;
    private TextView mScollClew = null;
    private boolean isFirstLoding = true;
    private DataQueryHandler mDataQueryHandler = null;
    private int mDistanceIndex = 0;
    private String[] mDistanceValue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.nearstorelist_main);

        mVisitTaskList = new ArrayList<VisitTaskInfo>();
        mDataQueryHandler = new DataQueryHandler(this.getContentResolver());
        mDistanceValue = this.getResources().getStringArray(R.array.distance_value);

        setupViews();
        initSpinner();
        //updateList();
    }

    public void onResume() {
        super.onResume();
        Actions.setAutoTime(this);
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mScrollView = (ObservableScrollView) findViewById(R.id.visitTaskcontent_scrollview);
        mScrollView.setScrollViewListener(mScrollViewListener);
        mScollClew = (TextView) findViewById(R.id.visitTask_scrollclew);
        mBodyLinearLayout = (LinearLayout) findViewById(R.id.visitTaskcontent_view_bodyView);
        mFrameLayout = (FrameLayout)findViewById(R.id.nearstorelistLayout);
        mNoneText = (TextView)findViewById(R.id.none_text);
        mSpinner = (Spinner) findViewById(R.id.nearstore_jiti);

        findViewById(R.id.visit_back).setOnClickListener(this);

        findViewById(R.id.visittask_task).setOnClickListener(this);
        findViewById(R.id.visittask_addstore).setOnClickListener(this);
        findViewById(R.id.visittask_nearstore).setOnClickListener(this);
        findViewById(R.id.visittask_back).setOnClickListener(this);
    }

    /**
     * 初始化距离
     */
    private void initSpinner() {
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.distance_type));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
            	TextView tv = (TextView)arg1;
                tv.setTextColor(getResources().getColor(R.color.white));
                mDistanceIndex = arg2;
                Log.e("zhu","initSpinner");
                isFirstLoding = true;
                if(mMyLocation == null){
            		mMyLocation = new MyLocation(NearStoreListActivity.this, true, false);
            	} 
                mMyLocation.getLocation(locationResult, false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    /**
     * 更新列表界面
     */
    private void updateView() {
    	mBodyLinearLayout.removeAllViews();
		View view = null;
		for (int i = 0; i < mVisitTaskList.size(); i++) {
			VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
			if(visitTaskInfo.isClosed){
                if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
                    view = getDealerClosedTaskItem(visitTaskInfo);
                }else{
                    view = getClosedTaskItem(visitTaskInfo);
                }
            } else if(visitTaskInfo.isVisited){
				if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
					view = getDealerVisitedTaskItem(visitTaskInfo);
				}else{
					view = getVisitedTaskItem(visitTaskInfo);
				}
			}else{
				if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
					view = getDealerVisitTaskItem(visitTaskInfo);
				}else{
					view = getVisitTaskItem(visitTaskInfo);
				}
			}
			mBodyLinearLayout.addView(view);
		}

		if(mBodyLinearLayout.getChildCount() > 0){
			mNoneText.setVisibility(View.GONE);
		}else{
			mNoneText.setVisibility(View.VISIBLE);
		}

        mScrollView.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(mScrollView.canScrollView()){
                    mScollClew.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 获取门店列表项界面
     * @param info 门店信息
     */
    private View getVisitTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.home_visittasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        ImageView task = (ImageView) row.findViewById(R.id.home_visitTast);
        //task.setTag(info);
        //task.setOnClickListener(this);
        if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
            task.setImageResource(R.drawable.icon_checkout);
        }else{
            if(info.hasRemind){
                task.setImageResource(R.drawable.unread_info_count);
            }else{
                task.setImageDrawable(null);
            }
        }
//        View map = row.findViewById(R.id.home_visitTastMap);
//        map.setTag(info);
//        map.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.home_visitTasRowContent: //拜访弹框
//                    VisitTaskInfo info = (VisitTaskInfo) v.getTag();
//                    if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
//                        gotoProductInfoActivity(info);
//                    }else{
//                        Actions.toastShort(this, this.getString(R.string.firstcheckin));
//                    }
                    popCheckView((VisitTaskInfo) v.getTag(), v);
                    break;
                case R.id.checkpop_checkmap: //地图
                	gotoMapActivity(mCheckingVisitTaskInfo);
                    break;
                case R.id.visittask_addstore: //新增门店列表
                    gotoStoreListActivity();
                    //gotoAddStoreActivity();
                    break;
                case R.id.visit_back:
                case R.id.visittask_back: //返回
                    if(isChange){
                        setResult(RESULT_OK);
                    }
                    finish();
                    break;
                case R.id.visittask_task:
                    if(isChange){
                        setResult(RESULT_OK);
                    }
                    finish();
                    break;
                case R.id.checkpop_close:
                    if (mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1) {
                        mFrameLayout.removeView(mCheckView);
                    }
                    break;
                case R.id.popcheck_blank:
                    break;
                case R.id.checkpop_checkin: //签入
                	startCheck(VisitTaskListActivity.CHECK_IN);
                    break;
                case R.id.checkpop_checkout: //签出
                	startCheck(VisitTaskListActivity.CHECK_OUT);
                    break;
                case R.id.home_visitTast: //拜访弹框
                    popCheckView((VisitTaskInfo) v.getTag(), v);
                    break;
                case R.id.checkpop_editcrc: //CRC信息
                    if(mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1){
                        mFrameLayout.removeView(mCheckView);
                    }
                    VisitTaskInfo info = (VisitTaskInfo) v.getTag();
                    gotoProductInfoActivity(info);
                    break;
                case R.id.checkpop_storepop: //门店属性
                    gotoStoreInfoActivity((VisitTaskInfo) v.getTag());
                    break;
            }
        }
    }

    /**
     * 跳转门店数据调查界面
     * @param info 门店信息
     */
    private void gotoStoreInfoActivity(VisitTaskInfo info) {
        Intent intent = new Intent(NearStoreListActivity.this, StoreInfoActivity.class);
        intent.putExtra(StoreInfoActivity.STR_TYPE, StoreInfoActivity.TYPE_FROMVISIT);
        intent.putExtra(StoreInfoActivity.STR_STOREID, info.id);
        startActivity(intent);
    }

    /**
     * 跳转门店CRC数据调查界面
     * @param info 门店信息
     */
    private void gotoProductInfoActivity(VisitTaskInfo info) {
    	Intent intent = null;
    	 if (info.type == VisitTaskInfo.STORE_DEALER) {
             intent = new Intent(NearStoreListActivity.this, DealerTaskListActivity.class);
         } else {
             intent = new Intent(NearStoreListActivity.this, ProductInfoListActivity.class);
         }
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", info);
        intent.putExtras(bundle);
        startActivityForResult(intent, UPDATE_DB);
    }

    /**
     * 跳转门店地图界面
     * @param info 门店信息
     */
    private void gotoMapActivity(VisitTaskInfo info) {
    	Intent intent = new Intent(this, MyLocationActivity.class);
        intent.putExtra("lng", info.mLongitude/*121.5200*/);
        intent.putExtra("lat", info.mLatitude/*31.2996*/);
        intent.putExtra("name", info.mName);
        intent.putExtra("addr", info.mAddress/*"上海市杨浦区五角场店"*/);
        startActivity(intent);
    }

    private void gotoAddStoreActivity() {
        Intent intent = new Intent(NearStoreListActivity.this, AddStoreActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转新增门店列表界面
     */
    private void gotoStoreListActivity(){
        Intent tent = new Intent(NearStoreListActivity.this, AddedStoreListActivity.class);
        startActivity(tent);
    }

    private void gotoVisitTaskActivity() {
        Intent intent = new Intent(NearStoreListActivity.this, VisitTaskListActivity.class);
        startActivity(intent);
    }

    /**
     * 弹出门店拜访选择框
     * @param visitTaskInfo 门店信息
     * @param view 列表项View
     */
    private void popCheckView(VisitTaskInfo visitTaskInfo, View view) {
        if(mCheckView == null){
            mCheckView = getLayoutInflater().inflate(R.layout.layout_popcheck, null);
            mCheckView.setOnClickListener(this);
            ImageView close = (ImageView) mCheckView.findViewById(R.id.checkpop_close);
            close.setOnClickListener(this);
            Button map = (Button)mCheckView.findViewById(R.id.checkpop_checkmap);
            map.setOnClickListener(this);
        }
        TextView name = (TextView) mCheckView.findViewById(R.id.checkpop_title);
        name.setText(visitTaskInfo.mName);
        Button checkin = (Button) mCheckView.findViewById(R.id.checkpop_checkin);
        Button checkout = (Button) mCheckView.findViewById(R.id.checkpop_checkout);
        Button crc = (Button) mCheckView.findViewById(R.id.checkpop_editcrc);
        Button property = (Button) mCheckView.findViewById(R.id.checkpop_storepop);
        property.setTag(visitTaskInfo);
        crc.setTag(visitTaskInfo);
        if(Actions.DEBUG){
            Log.e("zhu","time="+visitTaskInfo.mCheckinTime);
        }
        if(visitTaskInfo.mCheckinTime != null && visitTaskInfo.mCheckinTime.length() > 2){
            setButtonEnable(checkin, false, R.drawable.checkin_gray);
            if(visitTaskInfo.mCheckoutTime != null && visitTaskInfo.mCheckoutTime.length() > 2){
                setButtonEnable(checkout, false, R.drawable.checkout_gray);
            }else{
                setButtonEnable(checkout, true, R.drawable.checkout);
            }
            if(!visitTaskInfo.isClosed){
                setButtonEnable(crc, true, R.drawable.crc);
            }else{
                setButtonEnable(crc, false, R.drawable.crc_gray);
            }
            if(visitTaskInfo.iProperty == 0){
                setButtonEnable(property, false, R.drawable.property);
            }else{
                setButtonEnable(property, true, R.drawable.property_blue);
            }
        }else{
            setButtonEnable(checkout, false, R.drawable.checkout_gray);

            setButtonEnable(checkin, true, R.drawable.checkin);

            setButtonEnable(crc, false, R.drawable.crc_gray);

            setButtonEnable(property, false, R.drawable.property);
        }
        mCheckingButtom = (ImageView) view.findViewById(R.id.home_visitTast);
        mCheckingVisitTaskInfo = visitTaskInfo;
        mFrameLayout.addView(mCheckView);
    }

    /**
     * 设置按钮状态
     * @param button 按钮
     * @param isEnabled 开启
     * @param resId 图片资源ID
     */
    private void setButtonEnable(Button button, boolean isEnabled, int resId){
        if(isEnabled){
            button.setEnabled(true);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(0xff349a30);
            button.setOnClickListener(this);
        }else{
            button.setEnabled(false);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(0xffb0aeae);
            button.setOnClickListener(null);
        }
    }

    public void onDestroy() {
    	if(mMyLocation != null){
    		mMyLocation.destroy();
    	}
        super.onDestroy();
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                if(isChange){
                    setResult(RESULT_OK);
                }
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 返回事件处理
     */
    private boolean doBack(){
        if(mFrameLayout.indexOfChild(mCheckView) != -1){
            mFrameLayout.removeView(mCheckView);
            return true;
        }
        return false;
    }

    /**
     * 按键事件拦截
     */
    public boolean dispatchKeyEvent(KeyEvent event){
		if(isChecking){
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

    /**
     * 触摸事件拦截
     */
	public boolean dispatchTouchEvent(MotionEvent ev){
		if(isChecking){
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	/**
     * 签入签出
     * @param type 类型 签入OR签出
     */
    private void startCheck(int type){
        if(!Actions.isOpenedGpsAndNetwork(this, true)){
            return;
        }
        isChange = true;
    	mCurLocation = null;
    	isChecking = true;
    	mCurCheckType = type;
    	mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.INVISIBLE);
    	mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.INVISIBLE);
    	mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.VISIBLE);
    	TextView text = (TextView)mCheckView.findViewById(R.id.checkpop_animationText);
    	if(mCurCheckType == VisitTaskListActivity.CHECK_IN){
    		text.setText(R.string.checkining);
    	}else{
    		text.setText(R.string.checkouting);
    	}
    	ImageView view = (ImageView)mCheckView.findViewById(R.id.checkpop_animationImage);
    	mAnimation = (AnimationDrawable) view.getBackground();
    	mAnimation.setLevel(0);
    	mAnimation.start();
    	if(mMyLocation == null){
    		mMyLocation = new MyLocation(this, false, false);
    	}
    	mMyLocation.getLocation(locationResult, true);
    }

    /**
     * 签出OR签入结束
     */
    private void stopCheck(){
        boolean success = saveData();
        if(mCurCheckType == VisitTaskListActivity.CHECK_IN){
            mCheckingButtom.setImageResource(R.drawable.icon_checkout);
        }else{
            //mCheckingButtom.setImageResource(R.drawable.pop_check_disable);
            mCheckingButtom.setEnabled(false);
        }
        isChecking = false;
        mAnimation.stop();
        mFrameLayout.removeView(mCheckView);
        if(mCheckingVisitTaskInfo.isVisited){
            updateCheckView(mCheckingVisitTaskInfo);
        }
        mCheckingVisitTaskInfo = null;
        mCheckingButtom = null;
        mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.GONE);
    }

    /**
     * 定位结果
     */
    public LocationResult locationResult = new LocationResult() {

        public void gotLocation(final Location location) {
            // Got the location!
            if (location != null) {
                mCurLocation = location;
            }
            if(isFirstLoding){
            	isFirstLoding = false;
            	getData();
            }else{
            	stopCheck();
            }
        }
    };

    /**
     * 保存签入OR签出数据
     */
    private boolean saveData(){
        double lat = 0;
        double lng = 0;
        if(mCurLocation != null){
            lat = mCurLocation.getLatitude();
            lng = mCurLocation.getLongitude();
        }
        if(lat == 0 && lng == 0){
            Location location = Util.mGetGpsLocation.getLastLocation();
            if(location != null){
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
        }
        if(mCurCheckType == VisitTaskListActivity.CHECK_IN){
            mCheckingVisitTaskInfo.mCheckinTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckinInfo(this, mCheckingVisitTaskInfo, lat, lng, true);
            if(success){
                if(lat == 0 && lng == 0){
                    Actions.toastShort(this, getString(R.string.checkinsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkin_success));
                }
                return true;
            }else{
                mCheckingVisitTaskInfo.mCheckinTime = "";
                return false;
            }
        }else{
            mCheckingVisitTaskInfo.mCheckoutTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckoutInfo(this, mCheckingVisitTaskInfo, lat, lng);
            if(success){
                if(lat == 0 && lng == 0){
                    Actions.toastShort(this, getString(R.string.checkoutsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkout_success));
                }
                mCheckingVisitTaskInfo.isVisited = true;
                return true;
            }else{
                mCheckingVisitTaskInfo.mCheckoutTime = "";
                return false;
            }
        }
    }

    /**
     * 更新列表项数据
     * @param updateInfo 门店信息
     */
    private void updateCheckView(VisitTaskInfo updateInfo){
        int index = getViewIndex(updateInfo);
        if(index != -1){
            mBodyLinearLayout.removeViewAt(index);
        }
        VisitTaskInfo info = mVisitTaskList.get(index);
        View view = null;
        if(info.type == VisitTaskInfo.STORE_DEALER){
            view = getDealerVisitedTaskItem(info);
        }else{
            view = getVisitedTaskItem(info);
        }
        mBodyLinearLayout.addView(view, index);
    }

    /**
     * 获取拜访门店界面在列表中的索引
     * @param updateInfo 门店信息
     */
    private int getViewIndex(VisitTaskInfo updateInfo){
        VisitTaskInfo info = null;
        for(int i = 0; i < mVisitTaskList.size(); i++){
            info = mVisitTaskList.get(i);
            if(info.id == updateInfo.id){
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取已拜访任务列表项
     * @param info 门店信息
     */
    private View getVisitedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.visitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 获取歇业任务列表项
     * @param info 门店信息
     */
    private View getClosedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.visitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        //content.setTag(info);
        //content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        ImageView image = (ImageView) row.findViewById(R.id.visited_status);
        image.setImageResource(R.drawable.icon_off);
        return row;
    }

    /**
     * 获取经销商已拜访任务列表项
     * @param info 门店信息
     */
    private View getDealerVisitedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealvisitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 获取经销商歇业任务列表项
     * @param info 门店信息
     */
    private View getDealerClosedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealvisitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        //content.setTag(info);
        //content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        ImageView image = (ImageView) row.findViewById(R.id.dealvisited_status);
        image.setImageResource(R.drawable.icon_off);
        return row;
    }

    /**
     * 获取经销商拜访任务列表项
     * @param info 门店信息
     */
    private View getDealerVisitTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealer_visittasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        ImageView task = (ImageView) row.findViewById(R.id.home_visitTast);
        //task.setTag(info);
        //task.setOnClickListener(this);
        if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
            task.setImageResource(R.drawable.icon_checkout);
        }else{
            if(info.hasRemind){
                task.setImageResource(R.drawable.unread_info_count);
            }else{
                task.setImageDrawable(null);
            }
        }
//        ImageView map = (ImageView) row.findViewById(R.id.home_visitTastMap);
//        map.setTag(info);
//        map.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    private ObservableScrollView.ScrollViewListener mScrollViewListener = new ObservableScrollView.ScrollViewListener(){

        @Override
        public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx,
                int oldy) {
            // TODO Auto-generated method stub
            if(Actions.DEBUG){
                Log.e("zhu","onScrollChanged="+ Math.abs(y - oldy));
            }
            if(Math.abs(y - oldy) > 1){
                mScollClew.setVisibility(View.GONE);
            }
        }

    };

    /**
     * 开始获取数据
     */
    private void getData(){
    	if(mCurLocation == null){
    		mNoneText.setVisibility(View.VISIBLE);
    	}else{
    		startTaskListAsyncQuery();
    	}
    	mMyLocation.destroy();
    	mMyLocation = null;
    }

    /**
     * 获取客户数据
     */
    private void startTaskListAsyncQuery() {
        try {
        	mDataQueryHandler.startQuery(CPOS_LIST_QUERY_TOKEN, null,
                    SalesSettings.CustomerSColumns.CONTENT_URI,
                    null, null, null, null);
        	/*mDataQueryHandler.startQuery(TASK_LIST_QUERY_TOKEN, null,
                    SalesSettings.VisitedStoresColumns.CONTENT_URI,
                    null, null, null, null);*/
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新拜访信息数据
     * @param cursor
     */
    private void updateList(Cursor cursor) {
        mVisitTaskList.clear();

        String where = "";
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            final int itemnoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
            final int checkintimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            final int checkouttimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME);
            final int visitedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.VISITSTATUS);
            final int closedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CLOSE);

            while (cursor.moveToNext()) {
            	VisitTaskInfo visitTaskInfo = new VisitTaskInfo();
            	visitTaskInfo.mDbId = cursor.getLong(idIndex);
            	visitTaskInfo.id = cursor.getString(storeidIndex);
            	visitTaskInfo.itemId = cursor.getString(itemnoIndex);
            	visitTaskInfo.mCheckinTime = cursor.getString(checkintimeIndex);
            	visitTaskInfo.mCheckoutTime = cursor.getString(checkouttimeIndex);
            	visitTaskInfo.isVisited = cursor.getInt(visitedIndex) == 1 ? true : false;
            	visitTaskInfo.isClosed =  cursor.getInt(closedIndex) == 1 ? true : false;

            	//if(!visitTaskInfo.isClosed){
            		mVisitTaskList.add(visitTaskInfo);
                	if(where.length() == 0){
                		where = "cid = \"" + visitTaskInfo.id +"\"";
                	}else{
                		where += " OR cid = \"" + visitTaskInfo.id +"\"";
                	}
            	//}
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
            cursor.close();
        }

        try {
        	mDataQueryHandler.startQuery(CPOS_LIST_QUERY_TOKEN, null,
                    SalesSettings.CustomerSColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新客户数据
     * @param cursor
     */
    private void updateCustomerPosList(Cursor cursor) {
        if(mVisitTaskList != null){
            mVisitTaskList.clear();
        }
    	String where = "";
        try {
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ID);
            final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LAT);
            final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LNG);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_NAME);
            final int typeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE);
            final int addrIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS);
            final int propertyIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY);

            while (cursor.moveToNext()) {
            	String cid = cursor.getString(storeidIndex);
            	Double lat = Double.parseDouble(cursor.getString(latIndex));
            	Double lng = Double.parseDouble(cursor.getString(lngIndex));
            	//VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
            	VisitTaskInfo visitTaskInfo = new VisitTaskInfo();
            	visitTaskInfo.id = cid;
            	visitTaskInfo.mName = cursor.getString(nameIndex);
            	visitTaskInfo.type = Integer.parseInt(cursor.getString(typeIndex));
            	visitTaskInfo.mAddress = cursor.getString(addrIndex);
            	if(Actions.DEBUG){
            	    Log.e("zhu", cursor.getString(typeIndex));
            	}
             	visitTaskInfo.mLatitude = Double.parseDouble(cursor.getString(latIndex));
             	visitTaskInfo.mLongitude = Double.parseDouble(cursor.getString(lngIndex));
             	visitTaskInfo.iProperty = cursor.getInt(propertyIndex);
            	if(isNear(lat, lng)){
            		mVisitTaskList.add(visitTaskInfo);
            		if(where.length() == 0){
                		where = "storeid = \"" + visitTaskInfo.id +"\"";
                	}else{
                		where += " OR storeid = \"" + visitTaskInfo.id +"\"";
                	}
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
            cursor.close();
        }

        try {
        	if(where.length() > 1){
        		mDataQueryHandler.startQuery(CVISITED_LIST_QUERY_TOKEN, null,
                        SalesSettings.VisitedStoresColumns.CONTENT_URI,
                        null, where, null, null);
        	}else{
        		updateView();
        	}
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        //updateView();
    }

    /**
     * 更新拜访信息数据
     * @param cursor
     */
    private void updateVisitedList(Cursor cursor) {
        try {
        	final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            final int itemnoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
            final int checkintimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            final int checkouttimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME);
            final int visitedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.VISITSTATUS);
            final int closedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CLOSE);
            final int dtidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.DTASKACTUALID);

            while (cursor.moveToNext()) {
            	String cid = cursor.getString(storeidIndex);
            	VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
            	visitTaskInfo.mDbId = cursor.getLong(idIndex);
            	visitTaskInfo.id = cursor.getString(storeidIndex);
            	visitTaskInfo.itemId = cursor.getString(itemnoIndex);
            	visitTaskInfo.mCheckinTime = cursor.getString(checkintimeIndex);
            	visitTaskInfo.mCheckoutTime = cursor.getString(checkouttimeIndex);
            	visitTaskInfo.isVisited = cursor.getInt(visitedIndex) == 1 ? true : false;
            	visitTaskInfo.isClosed =  cursor.getInt(closedIndex) == 1 ? true : false;
            	visitTaskInfo.mDatingTaskActualID = cursor.getString(dtidIndex);
            	//if(visitTaskInfo.isClosed){
            		//mVisitTaskList.remove(visitTaskInfo);
            	//}
            	
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
            cursor.close();
        }

//        try {
//            mDataQueryHandler.startQuery(CREMIND_LIST_QUERY_TOKEN, null,
//                    SalesSettings.RemindsColumns.CONTENT_URI,
//                    null, null, null, null);
//        } catch (SQLiteException e) {
//            e.printStackTrace();
//        }
        updateView();
    }

    /**
     * 检查是否有提醒数据
     * @param cursor
     */
    private void updateStoreRemindInfoList(Cursor cursor) {
        try {
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.CUSTOMERID);
            final int timeIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.TIME);

            while (cursor.moveToNext()) {
                String cid = cursor.getString(cidIndex);
                if(cid != null && cid.trim().length() > 0){
                    VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
                    if(Long.parseLong(cursor.getString(timeIndex)) > System.currentTimeMillis()){
                        visitTaskInfo.hasRemind = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "update Remind ListData error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }

        updateView();
   }

    /**
     * 根据门店ID获取门店信息
     * @param sid 门店ID
     */
    private VisitTaskInfo getVisitTaskInfo(String sid){
    	for(int i = 0; i < mVisitTaskList.size(); i++){
    		VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
    		if(visitTaskInfo.id.equals(sid)){
    			return visitTaskInfo;
    		}
    	}
    	return null;
    }

    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case TASK_LIST_QUERY_TOKEN:
                    updateList(cursor);
                    break;
                case CPOS_LIST_QUERY_TOKEN:
                	updateCustomerPosList(cursor);
                	break;
                case CVISITED_LIST_QUERY_TOKEN:
                	updateVisitedList(cursor);
                	break;
                case CREMIND_LIST_QUERY_TOKEN:
                    updateStoreRemindInfoList(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case TASK_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 门店是否在选择范围内
     * @param lat
     * @param lng
     */
    private boolean isNear(double lat, double lng){
    	float neardistance = Float.parseFloat(mDistanceValue[mDistanceIndex]);
    	boolean isNear = false;
    	Location temLocation = new Location("PA");
    	temLocation.setLatitude(lat);
    	temLocation.setLongitude(lng);
    	//Location temLocationb = new Location("Pb");
    	//float[] results = new float[3];
    	//Location.distanceBetween(31.2295958303650000, 121.4811709410100000, lat, lng, results);
    	//Log.e("zhu","size="+results.length);
    	//Log.e("zhu","000="+results[0]);
    	//temLocationb.setLatitude(31.2295958303650000);
    	//temLocationb.setLongitude(121.4811709410100000);
    	float distance = mCurLocation.distanceTo(temLocation);//temLocationb.distanceTo(temLocation);
    	//Log.e("zhu","aaa="+Util.GetShortDistance(121.4811709410100000, 31.2295958303650000, lng, lat));
    	if(Actions.DEBUG){
    	    Log.e("zhu","distance="+distance);
    	}
    	if(distance <= neardistance){
    		isNear = true;
    	}
    	return isNear;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case UPDATE_DB:
                isChange = true;
                startTaskListAsyncQuery();
                break;
        }
    }
}
